package cn.swu.ws.webCounter;

import cn.swu.ws.dao.MysqlDbDao;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@WebFilter(urlPatterns = "/UserServlet")
public class WebTotalCounter extends HttpFilter {
    private int hitCount;
    public void  init(FilterConfig config) throws ServletException {
        // 重置点击计数器
        hitCount = 0;
        Connection connection;
        Statement statement;
        ResultSet resultSet;
        String sql = "select id,counter from WebPageCounter;";
        try {
            connection = MysqlDbDao.login_database();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()){
                hitCount = resultSet.getInt("counter");
                System.out.println("网站访问统计："+ hitCount);
                System.out.println(hitCount);;
            }
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public void  doFilter(ServletRequest request,
                          ServletResponse response,
                          FilterChain chain)
            throws java.io.IOException, ServletException {
        // 把计数器的值增加 1
        hitCount++;
        this.update();
        // 输出计数器
        System.out.println("网站访问统计："+ hitCount );
        // 把请求传回到过滤器链
        chain.doFilter(request,response);
    }
    public void destroy()
    {
        this.update();
    }
    private void update(){
        Connection connection;
        Statement statement;
        int resultSet;
        String sql_tem = "UPDATE WebPageCounter SET counter=%d WHERE id=1;";
        String sql = String.format(sql_tem, hitCount);
        try {
            connection = MysqlDbDao.login_database();
            statement = connection.createStatement();
            resultSet = statement.executeUpdate(sql);
            System.out.println("网站总在线人数修改成功");
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

